<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="员工姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryKeyword">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleImport">导入线索</el-button>
        </el-form-item>
        <el-form-item>
          <el-link type="primary" :underline="false" @click="handleExport">导出线索</el-link>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="empList" highlight-current-row v-loading="listLoading" @selection-change="selectChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="40">
      </el-table-column>
      <el-table-column prop="username" label="员工名称">
      </el-table-column>
      <el-table-column prop="headImage" label="头像">
        <template scope="scope">
          <img :src="scope.row.headImage" width="80px">
        </template>
      </el-table-column>
      <el-table-column prop="password" label="员工密码">
      </el-table-column>
      <el-table-column prop="age" label="年龄">
      </el-table-column>
      <el-table-column prop="email" label="邮箱">
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门">
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template scope="scope">
          <el-link type="primary" :underline="false" @click="handleRole(scope.$index, scope.row)"
                   style="margin-right: 10px">角色
          </el-link>
          <!--          <el-button size="small" @click="handleRole(scope.$index, scope.row)">添加角色</el-button>-->
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length === 0">批量删除</el-button>
      <el-pagination style="float: right;margin-top: 10px;" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 50]"
                     :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-col>

    <!-- 对话框 添加/修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" @close="dialogClose">
      <el-form :model="form" :rules="addFormRules">
        <el-input v-model="form.id" autocomplete="off" type="hidden"></el-input>
        <el-form-item label="账号" prop="username" style="width: 90%">
          <el-input v-model="form.username" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" style="width: 90%">
          <el-input v-model="form.password" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="年龄" style="width: 90%">
          <el-input v-model="form.age" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" style="width: 90%">
          <el-input v-model="form.email" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="头像" style="width: 90%">
          <el-input v-model="form.headImage" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>

        <el-form-item label="所属部门">
          <!-- <el-input v-model="form.managerId" autocomplete="off" style="width: 70%;"></el-input> -->
          <el-select v-model="form.department" placeholder="请选择" clearable value-key="id">
            <el-option :label="dept.name" :value="dept" v-for="dept in depts"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSure">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="角色" :visible.sync="dialogRoleVisible" @close="dialogClose">
      <el-form :model="roleform">
        <el-input v-model="roleform.id" autocomplete="off" type="hidden"></el-input>
        <el-form-item label="账号" style="width: 90%">
          <el-select v-model="roleform.roleId" placeholder="请选择">
            <el-option style="width: 100px"
                       v-for="item in roles"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="handleRoleClose">取 消</el-button>
        <el-button type="primary" @click="handleRoleSure">确 定</el-button>
      </div>
    </el-dialog>

    <!--文件上传-->
    <el-dialog class="update-dialog" title="导入线索" :visible.sync="dialogExcelVisible" @close="dialogClose">
      <el-upload class="upload"
                 ref="upload"
                 action="string"
                 :file-list="fileList"
                 :auto-upload="false"
                 :http-request="uploadFile"
                 :on-change="handleChange"
                 :on-preview="handlePreview"
                 :on-remove="handleRemove"
                 multiple="multiple">
        <el-button slot="trigger"
                   size="small"
                   type="primary"
                   @click="delFile">选取文件
        </el-button>
        <div slot="tip" class="el-upload__tip">只能上传Excel文件</div>
      </el-upload>
      <!--提交按钮-->
      <el-button type="primary" style="margin-left: 400px"
                 @click="onSubmit">提交
      </el-button>

    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    return {
      filters: {
        keyword: ''
      },
      empList: {},
      currentPage: 1,
      pageSize: 10,
      // 总记录数
      total: 0,
      listLoading: false,
      sels: [],//列表选中列
      dialogFormVisible: false,
      dialogRoleVisible: false,
      form: {},
      addFormRules: {
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      },
      depts: [],
      dialogTitle: '',
      roles: [],
      roleform: {
        id: null,
        employeeId: null,
        roleId: null
      },
      //以下是文件上传
      dialogExcelVisible: false,
      fileList: [],
      // 不支持多选
      multiple: false,
      formData: ""
    }
  },
  created() {
    this.loadDataPage();
    this.getDepts();
  },
  methods: {
    loadDataPage() {
      let pageQuery = {
        keyword: this.filters.keyword,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }
      this.$http.post("/emp", pageQuery).then(res => {
        this.empList = res.data.data.pageList
        this.total = res.data.data.count
      })
    },

    //改变每页总条数触发事件
    handleSizeChange(val) {
      this.pageSize = val
      this.loadDataPage();
    },
    //改变当前页触发事件
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadDataPage();
    },
    queryKeyword() {
      this.currentPage = 1;
      this.pageSize = 10;
      this.loadDataPage();
    },
    //打开对话框
    handleAdd() {
      this.dialogFormVisible = true
      this.dialogTitle = "添加";
    },
    //取消对话框
    handleClose() {
      this.dialogFormVisible = false;
      this.form = {};
    },
    //确定 发送添加/修改请求
    handleSure() {
      this.$confirm('确认提交吗？', '提示', {}).then(() => {
        this.$http.put('/emp', this.form).then((res) => {
          if (res.data.success) {
            this.$message({
              message: res.data.message,
              type: 'success'
            });
          } else {
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.dialogFormVisible = false;
          this.loadDataPage();
          this.form = {};
        });
      });
    },
    //编辑
    handleEdit(index, row) {
      this.dialogTitle = "修改"
      this.dialogFormVisible = true;
      // 复制数据，避免修改数据后点击取消仍会改变当前行数据的情况
      let copy = Object.assign({}, row)
      this.form = copy;//数据回显
    },
    // X
    dialogClose() {
      this.form = {}
    },
    //删除
    handleDel(row) {
      this.$confirm('确认删除吗？', '提示', {}).then(() => {
        this.$http.delete('/emp/' + row.id).then((res) => {
          if (res.data.success) {
            this.$message({
              message: res.data.message,
              type: 'success'
            });
          } else {
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.loadAfterDeleteLastData();
          this.loadDataPage();//刷新
        });
      });
    },
    //批量选择
    selectChange(val) {
      let delArray = [];
      for (let i = 0; i < val.length; i++) {
        delArray[i] = val[i].id
      }
      this.sels = delArray;
    },
    //批量删除
    batchRemove() {
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch('/emp', this.sels).then((res) => {
          this.$message({
            message: res.data.message,
            type: 'success'
          });
          this.loadAfterDeleteLastData();
          this.loadDataPage();
        });
      })
    },
    //获取员工列表，用于多选
    getDepts() {
      this.$http.get('/dept').then(res => {
        this.depts = res.data.data
      })
    },
    // 删除分页的最后一条数据后，跳到上一分页
    loadAfterDeleteLastData() {
      let deleteAfterPage = Math.ceil((this.total - 1) / this.pageSize)
      let deleteAfterCurrentPage = this.currentPage > deleteAfterPage ? deleteAfterPage : this.currentPage
      this.currentPage = deleteAfterCurrentPage < 1 ? 1 : deleteAfterCurrentPage
    },
    //为用户添加角色
    handleRole(index, row) {
      this.dialogRoleVisible = true;
      this.$http.get('/role').then(res => {
        this.roles = res.data.data;
      })
      // this.$http.get("/employeeRole/empId/"+row.id).then(res => {
      //   if(res.data.data){
      //     this.roleform.id = res.data.data.id
      //   }
      // })
      console.log(row)
      const empRole = row.employeeRole;
      let copy = Object.assign({}, empRole);
      this.roleform = copy;
      if (empRole === null) {
        this.roleform.employeeId = row.id
      }
      console.log(copy)
      console.log(this.roleform)
    },
    handleRoleClose() {
      this.dialogRoleVisible = false;
      this.roles = [];
    },
    handleRoleSure() {
      this.dialogRoleVisible = false;
      console.log(this.roleform)
      this.$http.put('/employeeRole', this.roleform).then(res => {
        this.$message({type: 'success', message: res.data.message})
        this.loadDataPage();

      })
      this.roleform = {}
    },
    /*=====================文件上传============================*/
    //导入Excel
    handleImport() {
      this.dialogExcelVisible = true;
    },
    //导出
    handleExport() {
      let pageQuery = {
        keyword: this.filters.keyword,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }
      // responseType: 'blob'不能省略，否则生成Excel会乱码
      this.$http.post('/emp/exportExcel', pageQuery,{responseType: 'blob'}).then(response => {
        // 创建一个blob对象
        const url = window.URL.createObjectURL(new Blob([response.data]));
        // 创建一个a标签用于下载
        const link = document.createElement('a');
        link.href = url;
        // 设置下载文件的名称
        const date = new Date();
        const filename = `${date.toISOString().slice(0, 10)}.xls`;
        link.setAttribute('download', filename);
        // 触发下载
        document.body.appendChild(link);
        link.click();
        // 清理
        document.body.removeChild(link);
      })
    },
    //点击上传文件触发的额外事件,清空fileList
    delFile() {
      this.fileList = [];
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      // console.log(this.fileList, "sb");
    },
    //自定义上传文件
    uploadFile(file) {
      this.formData.append("file", file.file);
      // console.log(file.file, "sb2");
    },
    //删除文件
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 点击文件
    handlePreview(file) {
      console.log(file);
    },
    //提交按钮
    onSubmit() {
      let formData = new FormData();
      formData.append("file", this.fileList[0].raw);//拿到存在fileList的文件存放到formData中
      //下面数据是我自己设置的数据,可自行添加数据到formData(使用键值对方式存储)
      // formData.append("title", this.title);
      this.$http.post('/emp/importExcel',formData,{"Content-Type": "multipart/form-data;charset=utf-8"})
          .then(res => {
        this.$message({type:'success',message:res.data.message});
      })
      this.loadDataPage();//刷新
      this.dialogExcelVisible = false;
      this.fileList = [];
    }
  }
}

</script>

<style scoped>

.upload{
  margin-bottom: 50px;
}
</style>